package com.jinzhi.jzweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.ExaminationResultsExportVo;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <pre>
 * 考场
 * </pre>
 * <small> 2020-02-24 21:00:12 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/examinationRoom")
public class ExaminationRoomController extends BaseController {
    @Autowired
    private ExaminationRoomService examinationRoomService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private CertificateProfileService certificateProfileService;
    @Autowired
    private OrganizationRolesService organizationRolesService;
    @Autowired
    private CertificateNewsService certificateNewsService;
    @Autowired
    private MsgService msgService;
    @Autowired
    private DictService dictService;


    @GetMapping()
    @RequiresPermissions("jzweb:examinationRoom:examinationRoom")
    String ExaminationRoom() {
        return "jzweb/examinationRoom/examinationRoom";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("jzweb:examinationRoom:examinationRoom")
    public Result<Page<ExaminationRoomDO>> list(HttpServletRequest req, ExaminationRoomDO examinationRoomDTO) {
        Wrapper<ExaminationRoomDO> wrapper = new EntityWrapper<ExaminationRoomDO>().orderBy("id", false);
        if (examinationRoomDTO.getName() != null) {
            wrapper.like("name", examinationRoomDTO.getName());
        }
        if (examinationRoomDTO.getType() != null) {
            wrapper.eq("type", examinationRoomDTO.getType());
        }
        if (examinationRoomDTO.getState() != null) {
            wrapper.eq("state", examinationRoomDTO.getState());
        }
        if (StringUtils.isNotBlank(examinationRoomDTO.getProfileName())) {
            Wrapper<CertificateProfileDO> cerWrapper = new EntityWrapper<CertificateProfileDO>().like("name", examinationRoomDTO.getProfileName());
            List<CertificateProfileDO> certificateProfileDOS = certificateProfileService.selectList(cerWrapper);
            String str = "";
            for (CertificateProfileDO certificateProfileDO : certificateProfileDOS) {
                str = str + certificateProfileDO.getId() + ",";
            }
            wrapper.and();
            if (StringUtils.isNotBlank(str)) {
                wrapper.in("profile_id", str.substring(0, str.length() - 1));
            } else {
                wrapper.eq("profile_id", null);
            }
        }

        String roleName = getRoleNames();//查询用户角色
        if (!roleName.contains("超级用户角色")) {
            Object orgId = req.getSession().getAttribute("orgId");
            if (orgId != null) {
                wrapper.eq("org_id", orgId);
            } else {
                wrapper.eq("org_id", this.getUser().getOrgId());
            }
        } else {
            if (StringUtils.isNotBlank(examinationRoomDTO.getOrgName())) {
                Wrapper<OrganizationNewsDO> orWrapper = new EntityWrapper<OrganizationNewsDO>().like("name", examinationRoomDTO.getOrgName());
                List<OrganizationNewsDO> organizationNewsDOS = organizationNewsService.selectList(orWrapper);
                String str = "";
                for (OrganizationNewsDO organizationNewsDO : organizationNewsDOS) {
                    str = str + organizationNewsDO.getId() + ",";
                }
                wrapper.and();
                if (StringUtils.isNotBlank(str)) {
                    wrapper.in("org_id", str.substring(0, str.length() - 1));
                } else {
                    wrapper.eq("org_id", null);
                }
            }
        }

        Page<ExaminationRoomDO> page = examinationRoomService.selectPage(getPage(ExaminationRoomDO.class), wrapper);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            ExaminationRoomDO obj = (ExaminationRoomDO) page.getRecords().get(i);
            if (obj.getCreaterId() != null) {
                UserDO userDO = userService.selectById(obj.getCreaterId());
                if (userDO != null) {
                    obj.setCreaterName(userDO.getUsername());
                }
            }
            if (obj.getCheckerId() != null) {
                UserDO userDO = userService.selectById(obj.getCheckerId());
                if (userDO != null) {
                    obj.setCheckerName(userDO.getUsername());
                }
            }
            if (obj.getOrgId() != null) {
                OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(obj.getOrgId());
                if (organizationNewsDO != null) {
                    obj.setOrgName(organizationNewsDO.getName());
                }
            }
            if (obj.getProfileId() != null) {
                CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(obj.getProfileId());
                if (certificateProfileDO != null) {
                    obj.setProfileName(certificateProfileDO.getName());
                }
            }
            list.add(obj);
        }
        page.setRecords(list);
        return Result.ok(page);
    }



    @GetMapping("/add")
    @RequiresPermissions("jzweb:examinationRoom:add")
    String add(Model model, HttpServletRequest req) {

        //查询用户角色
        String roleName = getRoleNames();
        if (!roleName.contains("超级用户角色")) {
            Object orgId = req.getSession().getAttribute("orgId");
            if (orgId != null) {
                List<OrganizationNewsDO> org = organizationNewsService.findByKv("id", orgId);
                model.addAttribute("orgRole", org);
            } else {
                List<OrganizationNewsDO> org = organizationNewsService.findByKv("id", this.getUser().getOrgId());
                model.addAttribute("orgRole", org);
            }

        } else {
            model.addAttribute("orgRole", organizationRolesService.selByRoleType(5));
        }

        return "jzweb/examinationRoom/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:examinationRoom:edit")
    String edit(@PathVariable("id") Long id, Model model, HttpServletRequest req) {
        //查询用户角色
        String roleName = getRoleNames();
        if (!roleName.contains("超级用户角色")) {
            Object orgId = req.getSession().getAttribute("orgId");
            if (orgId != null) {
                List<OrganizationNewsDO> org = organizationNewsService.findByKv("id", orgId);
                model.addAttribute("orgRole", org);
            } else {
                List<OrganizationNewsDO> org = organizationNewsService.findByKv("id", this.getUser().getOrgId());
                model.addAttribute("orgRole", org);
            }
        } else {
            model.addAttribute("orgRole", organizationRolesService.selByRoleType(5));
        }

        ExaminationRoomDO examinationRoom = examinationRoomService.selectById(id);
        model.addAttribute("examinationRoom", examinationRoom);
        return "jzweb/examinationRoom/edit";
    }

    @Log("查询考点对应的证书")
    @GetMapping("/selOrgByCer")
    @ResponseBody
    public Result<?> selOrgByCer(String orgId) {
        if (StringUtils.isNotBlank(orgId)) {
            List<Map<Object, Object>> cerListss = new ArrayList<>();
            Map map = new HashMap();
            map.put("roleType", 5);
            map.put("orgId", Long.parseLong(orgId));
            String cerIds = organizationRolesService.selByIdProName(map);
            if (cerIds != null) {
                List<String> cerLists = new ArrayList<>();
                String[] cers = cerIds.split(",");
                if (cers != null) {
                    for (int i = 0; i < cers.length; i++) {
                        cerLists.add(cers[i]);
                    }
                    map.clear();
                    map.put("cerIds", cerLists);
                    cerListss = certificateProfileService.selOrgByCer(map);
                }
            }
            return Result.ok(cerListss);
        } else {
            return Result.fail("请先选择考点！");
        }
    }

    @GetMapping("/info/{id}")
    @RequiresPermissions("jzweb:examinationRoom:examinationRoom")
    String info(@PathVariable("id") Long id, Model model) {
        ExaminationRoomDO examinationRoom = examinationRoomService.selectById(id);
        if (examinationRoom.getCreaterId() != null) {
            UserDO userDO = userService.selectById(examinationRoom.getCreaterId());
            if (userDO != null) {
                examinationRoom.setCreaterName(userDO.getUsername());
            }
        }
        if (examinationRoom.getCheckerId() != null) {
            UserDO userDO = userService.selectById(examinationRoom.getCheckerId());
            if (userDO != null) {
                examinationRoom.setCheckerName(userDO.getUsername());
            }
        }
        if (examinationRoom.getOrgId() != null) {
            OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(examinationRoom.getOrgId());
            if (organizationNewsDO != null) {
                examinationRoom.setOrgName(organizationNewsDO.getName());
            }
        }
        if (examinationRoom.getProfileId() != null) {
            String[] profilesId = examinationRoom.getProfileId().split(",");
            String returnK = null;
            for (int j = 0; j < profilesId.length; j++) {
                CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(Long.parseLong(profilesId[j]));
                if (certificateProfileDO != null) {
                    if (returnK == null) {
                        returnK = certificateProfileDO.getName();
                    } else {
                        returnK = returnK + "," + certificateProfileDO.getName();
                    }
                }
            }
            examinationRoom.setProfileName(returnK);
        }
        model.addAttribute("examinationRoom", examinationRoom);
        return "jzweb/examinationRoom/info";
    }

    @Log("添加考场")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:examinationRoom:add")
    public Result<String> save(ExaminationRoomDO examinationRoom) {
        examinationRoom.setCreaterId(this.getUserId());
        examinationRoomService.insert(examinationRoom);
        return Result.ok();
    }
    
    

    @Log("修改考场")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:examinationRoom:edit")
    public Result<String> update(ExaminationRoomDO examinationRoom) {
        examinationRoom.setState(0);
        boolean update = examinationRoomService.updateById(examinationRoom);
        return update ? Result.ok() : Result.fail();
    }

    @Log("删除考场")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:examinationRoom:remove")
    public Result<String> remove(Long id) {
        examinationRoomService.deleteById(id);
        return Result.ok();
    }

    @Log("批量删除考场")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:examinationRoom:batchRemove")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
        examinationRoomService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }

    @Log("审核")
    @PostMapping("/review")
    @ResponseBody
    @RequiresPermissions("jzweb:examinationRoom:review")
    public Result<String> review(@RequestParam("ids[]") Long[] ids, Integer state, String remark) {
        if (state.equals(2) || state.equals(1)) {

            //查询字典:消息模板
            DictDO dic = null;
            String valStr = "";
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (state == 2) {
                dic = dictService.findOneByKv("type", "check_no_pass");
                valStr = dic.getValue().replace("{value4}", remark);
            } else {
                dic = dictService.findOneByKv("type", "check_pass");
                valStr = dic.getValue();
            }
            valStr = valStr.replace("{value1}", "考场");
            valStr = valStr.replace("{value2}", this.getUser().getUsername());
            valStr = valStr.replace("{value3}", formatter.format(new Date()));

            int i = 0;
            for (Long id : ids) {
                ExaminationRoomDO examinationRoomDO = examinationRoomService.selectById(id);
                if (examinationRoomDO != null) {
                    MsgDO msg = new MsgDO();
                    examinationRoomDO.setState(state);
                    examinationRoomDO.setCheckerId(this.getUserId());
                    examinationRoomDO.setCheckerDate(new Date());
                    if (state.equals(2)) {
                        examinationRoomDO.setRemark(remark);//未通过，添加备注
                        msg.setTitle("考场审核未通过！");
                    } else {
                        examinationRoomDO.setRemark("");//审核通过，清空备注
                        msg.setTitle("考场审核通过！");
                    }
                    boolean b = examinationRoomService.updateById(examinationRoomDO);
                    if (b) {

                        msg.setContent(valStr);
                        msg.setUserId(examinationRoomDO.getCreaterId());
                        msg.setCreaterDate(new Date());
//						msg.setEnclosure();
                        msg.setType(0);
                        msg.setMsgType(0);
                        msg.setState(0);
                        msg.setCreaterId(this.getUserId());
                        msgService.insert(msg);

                        i++;
                    } else {
                        break;
                    }
                }
            }
            if (i == ids.length) {
                return Result.build(0, "已成功审核：" + i + "条数据");
            } else {
                return Result.fail("审核状态修改失败！");
            }
        } else {
            return Result.fail("审核状态修改失败！");
        }
    }
}
